from django.db import models
from openpyxl import Workbook

from project.models import Project


# Create your models here.
class Case(models.Model):
    objects: models.QuerySet

    name = models.CharField("用例名称", max_length=32)
    project = models.ForeignKey(
        Project, on_delete=models.CASCADE, related_name="ui_project"
    )
    fixtures = models.CharField("fixtures", max_length=32, null=True, default="")

    keywords = models.JSONField("关键字", max_length=10240)

    # todo: 生成excel文件保存到upload_yaml_cases这个路径下
    def save_excel(self, path):
        from .serializers import UICaseSerializer

        serializer = UICaseSerializer(self)
        json_data = serializer.data  # 得到json内容(字典格式)

        # 去除用例中不会用到的
        json_data.pop("id")
        json_data.pop("project")

        # 创建一个新的工作簿
        wb = Workbook()
        # 获取默认创建的工作表
        ws = wb.active

        for k, v in json_data.items():
            if k != "keywords":
                ws.append([k, v])  # 写入数据到excel的第1, 2行
            else:
                # 写入数据到excel的第三行
                temp = [k, list(v[0].keys())[0]]
                temp.extend(list(v[0].values())[0])
                ws.append(temp)
                # 写入数据到4-最后一行
                for line in v[1:]:
                    temp = ["", list(line.keys())[0]]
                    temp.extend(list(line.values())[0])
                    ws.append(temp)
        # 指定文件名和路径保存工作簿
        file_name = (
                path / f"test_{self.id}_{self.name}.xlsx"
        )  # 您可以根据需要更改文件名

        wb.save(file_name)
